package com.mornd.gulimall.apis.config;

import com.mornd.gulimall.common.core.utils.ServletUtil;
import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: mornd
 * @dateTime: 2023/8/21 - 23:22
 */

@Slf4j
@Configuration
@ComponentScan(basePackages = "com.mornd.gulimall.apis.**.*fallback") // 扫描feign fallback组件
public class FeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        RequestInterceptor requestInterceptor = requestTemplate -> {
            try {
                HttpServletRequest request = ServletUtil.getRequest();
                /**
                 * 同步请求中的 cookie
                 * 如果是登录后，浏览器请求中会携带 GULI_SESSION 的 cookie
                 * 而使用 feign 会创建新的request，此时不包含cookie
                 */
                String cookie = request.getHeader("Cookie");
                requestTemplate.header("Cookie", cookie);
            } catch (Exception e) {
                log.error("配置feign拦截器发生异常：" + e.getMessage());
            }
        };
        return requestInterceptor;
    }

}
